<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/23
 * Time: 22:33
 */

namespace app\admin\controller;

use think\Controller;
use think\Model;
class News extends Base
{
    public function index(){
        $data = input('param.');
        $whereData = [];
        //转换查询条件
        if(!empty($data['start_time']) && !empty($data['end_time']) && $data['end_time'] > $data['start_time']){
            $whereData['create_time'] = [
                ['gt',strtotime($data['start_time'])],
                ['lt',strtotime($data['end_time'])],
            ];
        }
        if(!empty($data['catid'])){
            $whereData['catid'] = intval($data['catid']);
        }
        if (!empty($data['title'])){
            $whereData['title'] = ['like','%'.$data['title'].'%'];
        }
        //模式一
//        $news = model('News')->getNews();
        //模式二：列表页面用laypage
//        page size  from  limit from size
        $this->getPageAndSize($data);

//        获取表里面的数据
        $news = model('News')->getLstByCondition($whereData, $this->from, $this->size);
//        获取满足条件总数
        $total = model('News')->getLstCountByCondition($whereData);
//        结合总数+size
        $pageTotal = ceil($total/$this->size);

        return $this->fetch('',[
            'cats' => config('cat.lists'),
            'news'=>$news,
            'pageTotal' => $pageTotal,
            'curr' => $this->page,
            'start_time' => empty($data['start_time']) ? '' : $data['start_time'],
            'end_time' => empty($data['end_time']) ? '' : $data['end_time'],
            'catid' => empty($data['catid']) ? '' : $data['catid'],
            'title' => empty($data['title']) ? '' : $data['title'],
        ]);
    }
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $validate = validate('News');
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            //入库操作
            try{
                $id = model('News')->add($data);
            }catch (\Exception $e){
                return $this->result('',0,'新增失败');
            }
            if ($id){
                return $this->result(['jump_url' => url('news/index')], 1, 'OK');
            }else{
                return $this->result('',0,'新增失败');
            }
        } else {
            return $this->fetch('', [
                'cats' => config('cat.lists')
            ]);
        }
    }
}